from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from .models import Character, GameSession, Floor, Monster, Item, Shop, ShopItem, Skill, CharacterSkill
from django.urls import reverse
import random
import json

@login_required
def game_home(request):
    character = get_object_or_404(Character, user=request.user)
    
    # 修改查询条件，确保获取最新的活跃游戏会话
    active_session = GameSession.objects.filter(
        character=character,
        is_active=True,
        current_hp__gt=0  # 确保角色还活着
    ).order_by('-started_at').first()  # 获取最新的会话
    
    context = {
        'character': character,
        'active_session': active_session
    }
    return render(request, 'game_core/home.html', context)

def generate_monsters_for_floor(floor_number):
    """根据楼层生成怪物"""
    monsters = []
    
    # 决定这层需要生成几只怪物
    if floor_number % 5 == 0:  # 每5层出现2只怪物
        monster_count = 2
    else:
        monster_count = 1
    
    # 决定怪物类型
    if floor_number % 12 == 0:  # 每12层出现首领
        monster_type = 'BOSS'
    elif floor_number % 8 == 0:  # 每8层出现精英
        monster_type = 'ELITE'
    else:
        monster_type = 'NORMAL'
    
    # 获取符合条件的怪物
    available_monsters = Monster.objects.filter(monster_type=monster_type)
    
    # 随机选择怪物
    for _ in range(monster_count):
        if available_monsters.exists():
            monster = available_monsters.order_by('?').first()
            monsters.append(monster)
    
    return monsters

@login_required
def start_game(request):
    character = get_object_or_404(Character, user=request.user)
    
    # 更新游戏次数
    character.games_played += 1
    character.save()
    
    # 结束所有进行中的游戏
    GameSession.objects.filter(
        character=character,
        is_active=True
    ).update(is_active=False)
    
    # 创建新的游戏会话
    session = GameSession.objects.create(
        character=character,
        current_floor=1,
        current_hp=character.base_hp
    )
    
    # 生成第一层的怪物
    monsters = generate_monsters_for_floor(1)
    session.current_monsters.add(*monsters)
    
    messages.success(request, "新的冒险开始了！")
    return redirect('game_core:continue_game', session_id=session.id)

@login_required
def continue_game(request, session_id):
    # 添加调试信息
    print(f"继续游戏 - Session ID: {session_id}")
    print(f"请求路径: {request.path}")
    
    # 获取游戏会话
    game_session = get_object_or_404(GameSession, id=session_id, character__user=request.user)
    
    # 重置所有技能冷却
    CharacterSkill.objects.filter(character=game_session.character).update(cooldown_remaining=0)
    
    # 初始化或更新 monster_data
    current_monsters = game_session.current_monsters.all()
    monster_data = {
        str(m.id): {
            'hp': m.hp,
            'defense_reduction': 0,
            'defense_reduction_duration': 0
        }
        for m in current_monsters
    }
    request.session['monster_data'] = monster_data
    
    # 验证上下文数据
    context = {
        'session': game_session,
        'character': game_session.character,
        'monsters': current_monsters,
        'debug_info': {
            'session_id': session_id,
            'user_id': request.user.id,
            'path': request.path
        }
    }
    
    # 打印调试信息
    print("Context data:", {
        'has_session': bool(context.get('session')),
        'has_character': bool(context.get('character')),
        'monsters_count': len(context.get('monsters', [])),
        'monster_data': monster_data  # 添加monster_data到调试信息
    })
    
    return render(request, 'game_core/game.html', context)

@login_required
def tower_view(request):
    character = get_object_or_404(Character, user=request.user)
    return render(request, 'game_core/tower.html', {'character': character})

@login_required
def floor_view(request, floor_id):
    floor = get_object_or_404(Floor, id=floor_id)
    if floor.game_session.character.user != request.user:
        messages.error(request, "你无权访问该楼层！")
        return redirect('game_core:home')
    return render(request, 'game_core/floor.html', {'floor': floor})

@login_required
def battle_view(request, floor_id):
    floor = get_object_or_404(Floor, id=floor_id)
    if floor.game_session.character.user != request.user:
        messages.error(request, "你无权访问该战斗！")
        return redirect('game_core:home')
    return render(request, 'game_core/battle.html', {'floor': floor})

@login_required
def shop_view(request, floor_id):
    floor = get_object_or_404(Floor, id=floor_id)
    if floor.game_session.character.user != request.user:
        messages.error(request, "你无权访问该商店！")
        return redirect('game_core:home')
    return render(request, 'game_core/shop.html', {'floor': floor})

@login_required
def character_upgrade(request):
    character = get_object_or_404(Character, user=request.user)
    return render(request, 'game_core/upgrade.html', {'character': character})

@login_required
def skill_management(request):
    character = get_object_or_404(Character, user=request.user)
    skills = character.characterskill_set.all()
    return render(request, 'game_core/skills.html', {
        'character': character,
        'skills': skills
    })

@login_required
def equip_skill(request, skill_id):
    character = get_object_or_404(Character, user=request.user)
    char_skill = get_object_or_404(CharacterSkill, id=skill_id, character=character)
    char_skill.is_equipped = True
    char_skill.save()
    return redirect('game_core:skills')

@login_required
def unequip_skill(request, skill_id):
    character = get_object_or_404(Character, user=request.user)
    char_skill = get_object_or_404(CharacterSkill, id=skill_id, character=character)
    char_skill.is_equipped = False
    char_skill.save()
    return redirect('game_core:skills')

@login_required
def save_game(request):
    character = get_object_or_404(Character, user=request.user)
    # 实现存档逻辑
    messages.success(request, "游戏已保存")
    return redirect('game_core:home')

@login_required
def load_game(request):
    character = get_object_or_404(Character, user=request.user)
    # 实现读档逻辑
    messages.success(request, "游戏已加载")
    return redirect('game_core:home')

def reduce_skill_cooldowns(character):
    """减少角色所有技能的冷却时间"""
    for char_skill in CharacterSkill.objects.filter(character=character):
        if char_skill.cooldown_remaining > 0:
            char_skill.cooldown_remaining -= 1
            char_skill.save()

def calculate_damage(attacker_attack, defender_defense, is_skill=False, skill_damage=None):
    """计算伤害
    返回: (伤害值, 是否命中, 是否暴击)
    """
    # 命中判定
    if random.random() < 0.05:  # 5%未命中
        return 0, False, False
        
    # 暴击判定
    is_crit = random.random() < 0.05  # 5%暴击
    
    # 基础伤害计算
    if is_skill and skill_damage is not None:
        base_damage = skill_damage
    else:
        base_damage = max(1, attacker_attack - defender_defense)
    
    # 伤害浮动 (±25%)
    damage_multiplier = random.uniform(0.75, 1.25)
    damage = base_damage * damage_multiplier
    
    # 暴击伤害
    if is_crit:
        damage *= 2
        
    return int(max(1, damage)), True, is_crit

def format_battle_message(message, hit=True, crit=False):
    """格式化战斗消息"""
    if not hit:
        return f'<span style="color: gray">【未命中】{message}</span>'
    elif crit:
        return f'<span style="color: red">【暴击】{message}</span>'
    return message

def reduce_debuff_durations(monster_data):
    """减少所有怪物的debuff持续时间"""
    for monster_id, data in monster_data.items():
        if data.get('defense_reduction_duration', 0) > 0:
            data['defense_reduction_duration'] -= 1
            if data['defense_reduction_duration'] <= 0:
                # 清除debuff
                data['defense_reduction'] = 0
                data['defense_reduction_duration'] = 0

@login_required
def battle_attack(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            monster_id = data.get('monster_id')
            
            # 获取当前游戏会话
            game_session = get_object_or_404(GameSession, 
                                           character__user=request.user, 
                                           is_active=True)
            character = game_session.character
            monster = get_object_or_404(Monster, id=monster_id)
            
            # 验证这个怪物是否是当前楼层的怪物
            current_monsters = game_session.current_monsters.all()
            if monster not in current_monsters:
                return JsonResponse({'status': 'error', 'message': '无效的目标'})
            
            # 获取或初始化怪物数据
            monster_data = request.session.get('monster_data', {})
            if not monster_data:
                monster_data = {
                    str(m.id): {
                        'hp': m.hp,
                        'defense_reduction': 0,
                        'defense_reduction_duration': 0
                    }
                    for m in current_monsters
                }
                request.session['monster_data'] = monster_data
            
            # 在计算伤害之前减少debuff持续时间
            reduce_debuff_durations(monster_data)
            request.session['monster_data'] = monster_data
            
            # 计算伤害（考虑防御力debuff）
            current_defense = monster.defense
            if monster_data[str(monster_id)].get('defense_reduction', 0) > 0:
                defense_reduction = monster_data[str(monster_id)]['defense_reduction'] / 100
                current_defense = int(current_defense * (1 - defense_reduction))
            
            damage, hit, crit = calculate_damage(character.base_attack, current_defense)
            
            # 更新怪物血量
            if hit:
                current_hp = monster_data[str(monster_id)]['hp']  # 使用当前的HP值
                new_monster_hp = max(0, current_hp - damage)
                monster_data[str(monster_id)]['hp'] = new_monster_hp
                request.session['monster_data'] = monster_data  # 确保更新session
            
            # 构建战斗消息
            battle_message = f'你对 {monster.name} 造成了 {damage} 点伤害！'
            battle_message = format_battle_message(battle_message, hit, crit)
            
            # 怪物反击
            counter_message = []
            counter_damage = 0
            for m in current_monsters:
                m_data = monster_data[str(m.id)]
                if m_data['hp'] > 0:  # 只有存活的怪物才能反击
                    m_damage, m_hit, m_crit = calculate_damage(m.attack, character.base_defense)
                    if m_hit:
                        counter_damage += m_damage
                    m_msg = f'{m.name} 反击造成 {m_damage} 点伤害！'
                    counter_message.append(format_battle_message(m_msg, m_hit, m_crit))
            
            battle_message += '\n' + '\n'.join(counter_message)
            
            # 更新玩家生命值
            game_session.current_hp = max(0, game_session.current_hp - counter_damage)
            game_session.save()
            
            # 检查战斗是否结束
            all_monsters_dead = all(m_data['hp'] <= 0 for m_data in monster_data.values())
            rewards = ''
            next_floor_url = None
            
            if all_monsters_dead:
                # 结算奖励
                total_gold = sum(Monster.objects.get(id=int(mid)).reward_gold 
                               for mid in monster_data.keys())
                character.gold += total_gold
                character.save()
                
                # 进入下一层并初始化新的monster_data
                _handle_floor_completion(game_session, character, request)
                
                # 添加下一层的URL
                next_floor_url = reverse('game_core:continue_game', kwargs={'session_id': game_session.id})
                
                rewards = f'\n获得{total_gold}金币！'
            
            # 构建怪物数据（使用monster_data中的当前值）
            monsters_data = {}
            for m_id, data in monster_data.items():
                m = Monster.objects.get(id=int(m_id))
                monsters_data[m_id] = {
                    'hp_percentage': (data['hp'] / m.hp) * 100,
                    'current_hp': data['hp'],  # 使用当前HP
                    'max_hp': m.hp,
                    'defense': m.defense,
                    'defense_reduction': data.get('defense_reduction', 0),
                    'defense_reduction_duration': data.get('defense_reduction_duration', 0)
                }
            
            # 在攻击结算后，减少技能冷却
            reduce_skill_cooldowns(character)
            
            # 获取更新后的技能状态
            skills_data = {
                str(skill.id): {
                    'cooldown': skill.cooldown_remaining,
                    'name': skill.skill.name
                }
                for skill in CharacterSkill.objects.filter(character=character)
            }
            
            response_data = {
                'status': 'success',
                'message': battle_message,
                'monsters_data': monsters_data,
                'player_hp_percentage': (game_session.current_hp / character.base_hp) * 100,
                'rewards': rewards if rewards else None,
                'next_floor_url': next_floor_url,
                'skills_data': skills_data
            }
            
            return JsonResponse(response_data)
            
        except Exception as e:
            import traceback
            print(traceback.format_exc())
            return JsonResponse({'status': 'error', 'message': str(e)})
    
    return JsonResponse({'status': 'error', 'message': '无效的请求方法'})

def calculate_monster_attack(monster, character):
    """计算怪物反击伤害"""
    session = GameSession.objects.get(character=character, is_active=True)
    hit_roll = random.random()
    
    if hit_roll < 0.05:  # 5%概率未命中
        return {
            'monster_damage': 0,
            'monster_attack_type': 'miss'
        }
    
    base_damage = max(1, monster.attack - character.base_defense)
    damage_variation = random.uniform(0.75, 1.25)
    
    if hit_roll > 0.95:  # 5%概率暴击
        damage_variation *= 2
        attack_type = 'critical'
    else:
        attack_type = 'normal'
    
    damage = int(base_damage * damage_variation)
    session.current_hp = max(0, session.current_hp - damage)
    session.save()
    
    return {
        'monster_damage': damage,
        'monster_attack_type': attack_type,
        'player_hp_percentage': (session.current_hp / character.base_hp) * 100
    }

class SkillEffect:
    def __init__(self, char_skill, character, session, monster_data, target_id=None):
        self.char_skill = char_skill
        self.character = character
        self.session = session
        self.monster_data = monster_data
        self.target_id = target_id
        self.battle_message = ""
        
    def execute(self):
        """执行技能效果并返回统一格式的结果"""
        skill_type = self.char_skill.skill.skill_type
        skill_name = self.char_skill.skill.name
        
        # 根据技能名称调用对应的处理方法
        if skill_name == '回复':
            result = self._execute_heal()
        elif skill_name == '碎甲':
            result = self._execute_armor_break()
        else:  # 默认为攻击技能
            result = self._execute_attack()
        
        # 如果技能执行成功，处理怪物反击
        if result:
            self._handle_monster_counter_attack()
        
        # 设置技能冷却
        self.char_skill.cooldown_remaining = self.char_skill.skill.cooldown
        self.char_skill.save()
        
        return result

    def _execute_heal(self):
        """处理回复技能"""
        heal_percentage = self.char_skill.skill.base_value + (self.char_skill.current_level - 1) * self.char_skill.skill.level_value
        heal_amount = int(self.character.base_hp * heal_percentage / 100)
        
        self.session.current_hp = min(self.session.current_hp + heal_amount, self.character.base_hp)
        self.session.save()
        
        self.battle_message = f'使用{self.char_skill.skill.name}恢复了{heal_amount}点生命值！'
        return True

    def _execute_armor_break(self):
        """处理碎甲技能"""
        if not self.target_id:
            return False
            
        defense_reduction = self.char_skill.skill.base_value + (self.char_skill.current_level - 1) * self.char_skill.skill.level_value
        
        # 更新目标怪物的防御降低状态
        monster_id = str(self.target_id)
        if monster_id in self.monster_data:
            self.monster_data[monster_id].update({
                'defense_reduction': defense_reduction,
                'defense_reduction_duration': 5,  # 设置持续时间
                'original_defense': Monster.objects.get(id=self.target_id).defense  # 保存原始防御力
            })
        
        monster = Monster.objects.get(id=self.target_id)
        self.battle_message = f'使用{self.char_skill.skill.name}降低了{monster.name}的防御力{defense_reduction}%！'
        return True

    def _execute_attack(self):
        """处理攻击类技能"""
        if not self.target_id:
            return False
            
        monster = Monster.objects.get(id=self.target_id)
        monster_data = self.monster_data[str(self.target_id)]
        
        # 计算技能基础伤害
        skill_damage = self.char_skill.skill.base_value + (self.char_skill.current_level - 1) * self.char_skill.skill.level_value
        
        # 获取怪物当前防御力（考虑debuff）
        current_defense = monster.defense
        if monster_data.get('defense_reduction', 0) > 0:
            defense_reduction = monster_data['defense_reduction'] / 100
            current_defense = int(current_defense * (1 - defense_reduction))
        
        # 计算实际伤害
        damage, hit, crit = calculate_damage(
            self.character.base_attack, 
            current_defense,
            is_skill=True,
            skill_damage=skill_damage
        )
        
        if hit:
            current_hp = monster_data['hp']
            new_hp = max(0, current_hp - damage)
            monster_data['hp'] = new_hp
            
        message = f'使用{self.char_skill.skill.name}对{monster.name}造成了{damage}点伤害！'
        self.battle_message = format_battle_message(message, hit, crit)
        return True

    def _handle_monster_counter_attack(self):
        """处理怪物反击"""
        counter_messages = []
        counter_damage = 0
        
        # 获取所有存活的怪物
        for monster_id, data in self.monster_data.items():
            if data['hp'] > 0:  # 只有存活的怪物才能反击
                monster = Monster.objects.get(id=int(monster_id))
                damage, hit, crit = calculate_damage(monster.attack, self.character.base_defense)
                if hit:
                    counter_damage += damage
                counter_msg = f'{monster.name} 反击造成 {damage} 点伤害！'
                counter_messages.append(format_battle_message(counter_msg, hit, crit))
        
        # 更新玩家生命值
        self.session.current_hp = max(0, self.session.current_hp - counter_damage)
        self.session.save()
        
        # 添加反击消息
        if counter_messages:
            self.battle_message += '\n' + '\n'.join(counter_messages)

@login_required
def battle_use_skill(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            skill_id = data.get('skill_id')
            target_id = data.get('target_id')
            
            print(f"收到技能请求 - skill_id: {skill_id}, target_id: {target_id}")
            
            # 获取基础数据
            character = get_object_or_404(Character, user=request.user)
            char_skill = get_object_or_404(CharacterSkill, id=skill_id, character=character)
            session = get_object_or_404(GameSession, character=character, is_active=True)
            
            # 获取当前楼层的怪物
            current_monsters = session.current_monsters.all()
            print(f"当前楼层怪物: {[m.id for m in current_monsters]}")
            
            # 获取或初始化怪物数据
            monster_data = request.session.get('monster_data', {})
            if not monster_data:
                monster_data = {
                    str(m.id): {
                        'hp': m.hp,
                        'defense_reduction': 0,
                        'defense_reduction_duration': 0
                    }
                    for m in current_monsters
                }
                request.session['monster_data'] = monster_data
            
            print(f"Monster data: {monster_data}")
            
            # 验证目标是否有效（对于需要目标的技能）
            if char_skill.skill.name != '回复':  # 回复技能不需要目标
                if not target_id:
                    return JsonResponse({'status': 'error', 'message': '需要选择目标'})
                
                if str(target_id) not in monster_data:
                    return JsonResponse({'status': 'error', 'message': '无效的目标'})
            
            # 在执行技能效果之前减少debuff持续时间
            reduce_debuff_durations(monster_data)
            request.session['monster_data'] = monster_data
            
            # 执行技能效果
            skill_effect = SkillEffect(char_skill, character, session, monster_data, target_id)
            if not skill_effect.execute():
                return JsonResponse({'status': 'error', 'message': '技能使用失败'})
            
            # 检查战斗是否结束
            all_monsters_dead = all(m_data['hp'] <= 0 for m_data in monster_data.values())
            rewards = ''
            next_floor_url = None
            
            if all_monsters_dead:
                # 结算奖励
                total_gold = sum(Monster.objects.get(id=int(mid)).reward_gold 
                               for mid in monster_data.keys())
                character.gold += total_gold
                character.save()
                
                # 进入下一层并初始化新的monster_data
                _handle_floor_completion(session, character, request)
                
                # 添加下一层的URL
                next_floor_url = reverse('game_core:continue_game', kwargs={'session_id': session.id})
                
                rewards = f'\n获得{total_gold}金币！'
            
            # 构建怪物数据
            monsters_data = {}
            for monster_id, data in monster_data.items():
                monster = Monster.objects.get(id=int(monster_id))
                monsters_data[monster_id] = {
                    'hp_percentage': (data['hp'] / monster.hp) * 100,
                    'current_hp': data['hp'],
                    'max_hp': monster.hp,
                    'defense': monster.defense,
                    'defense_reduction': data.get('defense_reduction', 0),
                    'defense_reduction_duration': data.get('defense_reduction_duration', 0)
                }
            
            # 构建响应数据
            response_data = {
                'status': 'success',
                'message': skill_effect.battle_message + (rewards if rewards else ''),
                'monsters_data': monsters_data,
                'player_hp_percentage': (session.current_hp / character.base_hp) * 100,
                'rewards': rewards if rewards else None,
                'next_floor_url': next_floor_url,
                'skills_data': {
                    str(skill.id): {
                        'cooldown': skill.cooldown_remaining,
                        'name': skill.skill.name
                    }
                    for skill in CharacterSkill.objects.filter(character=character)
                }
            }
            
            return JsonResponse(response_data)
            
        except Exception as e:
            import traceback
            print(traceback.format_exc())
            return JsonResponse({'status': 'error', 'message': str(e)})
    
    return JsonResponse({'status': 'error', 'message': '无效的请求方法'})

@login_required
def shop_buy_item(request):
    # 实现购买物品逻辑
    return JsonResponse({'status': 'success'})

@login_required
def treasure_view(request, floor_id):
    floor = get_object_or_404(Floor, id=floor_id)
    if floor.game_session.character.user != request.user:
        messages.error(request, "你无权访问该宝藏房间！")
        return redirect('game_core:home')
    return render(request, 'game_core/treasure.html', {'floor': floor})

@login_required
def rest_view(request, floor_id):
    floor = get_object_or_404(Floor, id=floor_id)
    if floor.game_session.character.user != request.user:
        messages.error(request, "你无权访问该休息点！")
        return redirect('game_core:home')
    return render(request, 'game_core/rest.html', {'floor': floor})

@login_required
def upgrade_stat(request):
    if request.method == 'POST':
        character = get_object_or_404(Character, user=request.user)
        stat_type = request.POST.get('stat_type')
        
        # 计算升级费用
        if stat_type == 'hp':
            cost = character.base_hp * 10
            if character.gold >= cost:
                character.gold -= cost
                character.base_hp += 10
                messages.success(request, f"生命值提升10点！当前生命值：{character.base_hp}")
            else:
                messages.error(request, "金币不足！")
        
        elif stat_type == 'attack':
            cost = character.base_attack * 10
            if character.gold >= cost:
                character.gold -= cost
                character.base_attack += 2
                messages.success(request, f"攻击力提升2点！当前攻击力：{character.base_attack}")
            else:
                messages.error(request, "金币不足！")
        
        elif stat_type == 'defense':
            cost = character.base_defense * 10
            if character.gold >= cost:
                character.gold -= cost
                character.base_defense += 1
                messages.success(request, f"防御力提升1点！当前防御力：{character.base_defense}")
            else:
                messages.error(request, "金币不足！")
        
        character.save()
        
    return redirect('game_core:upgrade')

@login_required
def upgrade_skill(request):
    if request.method == 'POST':
        character = get_object_or_404(Character, user=request.user)
        skill_id = request.POST.get('skill_id')
        
        try:
            char_skill = CharacterSkill.objects.get(id=skill_id, character=character)
            
            # 检查是否达到最高等级
            if char_skill.current_level >= char_skill.skill.max_level:
                messages.error(request, "技能已达到最高等级！")
                return redirect('game_core:upgrade')
            
            # 计算升级费用
            cost = char_skill.current_level * 50
            
            if character.gold >= cost:
                character.gold -= cost
                char_skill.current_level += 1
                
                character.save()
                char_skill.save()
                
                messages.success(request, f"{char_skill.skill.name}升级成功！当前等级：{char_skill.current_level}")
            else:
                messages.error(request, "金币不足！")
                
        except CharacterSkill.DoesNotExist:
            messages.error(request, "技能不存在！")
    
    return redirect('game_core:upgrade')

@login_required
def skill_shop(request):
    character = get_object_or_404(Character, user=request.user)
    
    # 获取所有可学习的技能
    learned_skills = character.characterskill_set.values_list('skill_id', flat=True)
    available_skills = Skill.objects.exclude(id__in=learned_skills)
    
    context = {
        'character': character,
        'available_skills': available_skills,
    }
    return render(request, 'game_core/skill_shop.html', context)

@login_required
def learn_skill(request):
    if request.method == 'POST':
        character = get_object_or_404(Character, user=request.user)
        skill_id = request.POST.get('skill_id')
        
        try:
            skill = Skill.objects.get(id=skill_id)
            
            # 检查是否已学习
            if CharacterSkill.objects.filter(character=character, skill=skill).exists():
                messages.error(request, "已经学习过该技能！")
                return redirect('game_core:skill_shop')
            
            # 检查金币是否足够
            if character.gold >= skill.cost:
                character.gold -= skill.cost
                character.save()
                
                # 创建角色技能关联
                CharacterSkill.objects.create(
                    character=character,
                    skill=skill,
                    current_level=skill.base_level
                )
                
                messages.success(request, f"成功学习技能：{skill.name}")
            else:
                messages.error(request, "金币不足！")
                
        except Skill.DoesNotExist:
            messages.error(request, "技能不存在！")
    
    return redirect('game_core:skill_shop')

def _handle_floor_completion(session, character, request):
    """处理楼层完成后的逻辑"""
    # 进入下一层
    session.current_floor += 1
    
    # 生成新的怪物
    new_monsters = generate_monsters_for_floor(session.current_floor)
    session.current_monsters.clear()
    session.current_monsters.add(*new_monsters)
    
    # 初始化新的monster_data
    monster_data = {
        str(m.id): {
            'hp': m.hp,
            'defense_reduction': 0,
            'defense_reduction_duration': 0
        }
        for m in new_monsters
    }
    request.session['monster_data'] = monster_data
    
    session.save()